package cn.dyp.com.automaticcontrolserver.action;


import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Element;

import android.content.Context;
import android.content.Intent;

import cn.dyp.com.automaticcontrolserver.bean.Controller;
import cn.dyp.com.automaticcontrolserver.util.Util;

/**
 * @author zongbingwu 设置所有控制器状态的请求处理类
 */
public class ControlAction extends BaseAction {
	// action name
	public static final String TAG = "control";

	private Context context;

	public ControlAction(Context context) {
		this.context = context;
	}

	// jason协议的解析函数
	@Override
	protected String jasonPorcess(String param) {
		JSONObject jsonResponse = new JSONObject();
		try {
			JSONObject jsonRequest = new JSONObject(param);
			// 处理控制器请求
			String controlDevices[] = { Controller.WATER_PUMP_CONTORL,
					Controller.BLOWER_CONTORL, Controller.ROADLAMP_CONTORL,
					Controller.BUZZER_CONTORL };
			for (String device : controlDevices) {
				// 依次从报文中解析出各个控制器的值，然后向串口service发送广播进行控制
				if (jsonRequest.has(device)) {
					int isOpen = jsonRequest.getInt(device);
					controlDevice(device, isOpen);

					// set log string
					if (!logMsg.equals("")) {
						logMsg += ",";
					}
					if (isOpen > 0) {
						logMsg += "Open " + device;
					} else {
						logMsg += "Close " + device;
					}
					logObj = device;
				}
			}
			// 返回结果
			jsonResponse.put("result", "ok");
			return jsonResponse.toString();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// soap协议的解析函数
	@Override
	protected String soapPorcess(String param) {
		String ret = "failed";
		// 从完整的soap协议内容中解析出soap body内容
		Element soapBodyEle = Util.getSoapBodyElement(param);
		if (soapBodyEle != null) {
			// 控制器名称数组
			String controlDevices[] = { Controller.WATER_PUMP_CONTORL,
					Controller.BLOWER_CONTORL, Controller.ROADLAMP_CONTORL,
					Controller.BUZZER_CONTORL };
			for (String device : controlDevices) {
				// 依次从报文中解析出各个控制器的值，然后向串口service发送广播进行控制
				Element childEle = (Element) soapBodyEle.getElementsByTagName(
						device).item(0);
				if (childEle != null) {
					int isOpen = Integer.parseInt(childEle.getFirstChild()
							.getNodeValue());
					controlDevice(device, isOpen);
					ret = "ok";

					// set log string
					if (!logMsg.equals("")) {
						logMsg += ",";
					}
					if (isOpen > 0) {
						logMsg += "Open " + device;
					} else {
						logMsg += "Close " + device;
					}
					logObj = device;
				}
			}
		}
		// 返回结果
		return Util.getSoapXml(Util.getXmlElementStr("result", ret));
	}

	// 向串口service发送广播,控制外设的开启与关闭
	private void controlDevice(String device, int isOpen) {
		Intent intent = new Intent(
				"com.lenovo.agriculture.server.broadcat.senttoserialport");
		intent.putExtra("message", "control");
		intent.putExtra("device", device);
		intent.putExtra("isOpen", isOpen);
		context.sendBroadcast(intent);
	}

}
